package monitor;

import gnu.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


public class SerialComm implements SerialPortEventListener{
    @SuppressWarnings("rawtypes")
	static Enumeration			portList;
    static CommPortIdentifier	portId;
    static SerialPort			serialPort;
    static InputStream			in;

    static boolean portOpened = false;
    static String defaultPort = "/dev/tty.Pebble-SPP";

    private List<StreamEventListener> streamListeners = new ArrayList<StreamEventListener>();

    public SerialComm() {
    	super();
    }

    public SerialComm(String portname) {
    	super();
    	defaultPort = portname;
    }

    public void addStreamListener(StreamEventListener listener) {
    	streamListeners.add(listener);
    }

    public void removeStreamListener(StreamEventListener listener) {
    	streamListeners.remove(listener);
    }

    protected void notifyListeners(StreamEvent e) {
    	for (StreamEventListener listener : streamListeners) {
    		listener.streamAvailable(e);
    	}
    }

	public boolean connect() {
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
		    portId = (CommPortIdentifier) portList.nextElement();

		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (portId.getName().equals(defaultPort)) {
				    try {
				    	serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);
					    System.out.println("Opened port " + defaultPort);
					    try {
							serialPort.addEventListener(this);
						    serialPort.notifyOnDataAvailable(true);
						} catch (TooManyListenersException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					    try {
							in = serialPort.getInputStream();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				    	portOpened = true;
				    } catch (PortInUseException e) {
				    	System.out.println("Port in use.");
				    	continue;
				    }

				    try {
				    	serialPort.setSerialPortParams(9600,
								       SerialPort.DATABITS_8,
								       SerialPort.STOPBITS_1,
								       SerialPort.PARITY_NONE);
				    } catch (UnsupportedCommOperationException e) {}


				}
		    }
		}
		return portOpened;
	}

	public void close() {
		if (portOpened) {
			serialPort.close();
			portOpened = false;
		}
	}


//	private int beginCounter=30 ;

	@Override
	public void serialEvent(SerialPortEvent arg0) {
		// TODO Auto-generated method stub
        byte[] buffer = new byte[1024];
        int data;

        try
        {
            int len = 0;
            while ( ( data = in.read()) > -1 )
            {
//            	if(data=='s')
//               { len = 0;
////            	System.out.println("Stream event string "+(char)data);
//            	break;
//               }
            	if ( data == 0 ) {
            		continue;
            	} else if ( data == '\n' ) {
//                	System.out.println("Stream event string"+data);
                    break;
                }
                buffer[len++] = (byte) data;
            }
            if (buffer[len-1] == '\r')
            	len--;
            String str = new String(buffer,0,len);
//            System.out.println("Stream event string "+str);

        //start call the listener after begincounter times.
        // skip  the data at the beginning

//            if(beginCounter>0)
//            {beginCounter--;}
//            else
//            {
            	notifyListeners(new StreamEvent(str));
//            }


        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }

	}

}
